<?php

/**
 * 后台文章栏目模块 Model
 * ============================================================================
 * TBlog TBlog博客系统　BY Tmac PHP MVC framework
 * $Author: xing7878@gmail.com $  <zwttmac@qq.com>
 * $Id: category.class.php 52 2011-07-20 03:50:42Z xing7878@gmail.com $
 * http://www.t-mac.org；
 */
class category extends Model
{

    private $category_table;
    private $add_category_table;

    /**
     * 初始化变量　定义私有变量
     */
    public function _init()
    {
        //连接数据库
        $this->connect();
        $this->category_table = '#@__category';
        $this->add_category_table = '#@__addoncategory';
    }

    /**
     * 保存栏目分类
     * @param string $menusMain
     * return Boole
     */
    public function addClass($info, $mode = 'INSERT', $where = '')
    {
        $rs = $this->db->autoExecute($this->category_table, $info, $mode, $where);
        return $rs;
    }

    /**
     * 保存栏目分类
     * @param string $menusMain
     * return Boole
     */
    public function addClassReturn($info, $mode = 'INSERT', $where = '')
    {
        $rs = $this->db->autoInsertReturn($this->category_table, $info, $mode, $where);
        return $rs;
    }

    /**
     * 保存地方站的附加分类
     * @param string $menusMain
     * return Boole
     */
    public function addOnClass($info, $mode = 'INSERT', $where = '')
    {
        $rs = $this->db->autoExecute($this->add_category_table, $info, $mode, $where);
        return $rs;
    }

    /**
     * 获取一个资讯栏目信息
     * @param int $class_id 栏目id
     * return array
     */
    public function getCategoryInfo($class_id, $uid)
    {
        $rs = $this->db->getRow("SELECT * FROM $this->category_table WHERE cat_id = $class_id LIMIT 0,1");
        if ($uid > 1) {
            $add_cate_rs = $this->db->getRow("SELECT * FROM $this->add_category_table WHERE cat_id = $class_id AND uid=$uid LIMIT 0,1");                        
            if ($add_cate_rs) {
                $rs['cat_pid'] = $add_cate_rs['cat_pid'];
                $rs['cat_name'] = $add_cate_rs['cat_name'];
                $rs['channeltype'] = $add_cate_rs['channeltype'];
                $rs['category_keywords'] = $add_cate_rs['category_keywords'];
                $rs['category_description'] = $add_cate_rs['category_description'];
                $rs['category_content'] = $add_cate_rs['content'];
            }
        }        
        return $rs;
    }

    /**
     * 获取一个附加栏目表信息
     * @param int $class_id 栏目id
     * return array
     */
    public function getAddCategoryInfo($class_id, $uid)
    {
        $rs = $this->db->getRow("SELECT cat_id FROM $this->add_category_table WHERE cat_id = $class_id AND uid = $uid LIMIT 0,1");
        return $rs;
    }

    /**
     * 获取资讯栏目
     * return article_class,pages
     */
    public function getCategory($uid, $reid, $level)
    {
        global $elo; //定义全局变量 返回值
        $prefix_space = "";
        for ($i = 0; $i < $level; $i++) {
            $prefix_space .= "　"; //第一级就增加一个缩进
        }
        if ($uid > 1) {
            $sqltree = "SELECT a.*, b.content AS category_content FROM $this->category_table a LEFT JOIN $this->add_category_table b ON a.cat_id = b.cat_id AND a.uid = b.uid WHERE a.cat_pid = " . $reid . " AND (a.uid = '{$uid}' OR a.uid = 1) AND a.cat_type = 0 ORDER BY a.cat_order DESC, a.cat_id ASC";
        } else {
            $sqltree = "SELECT * FROM $this->category_table WHERE cat_pid = " . $reid . "  AND uid = 1 ORDER BY cat_order DESC, cat_id ASC";
        }
        $rs = $this->db->getAll($sqltree);
        $fuhao = $level == 0 ? '' : '|-';
        if (is_array($rs)) {
            foreach ($rs as $k => $v) {
                $category_content = Functions::cut_str(strip_tags($v['category_content']), 42);
                $elo .= "<tr onmouseout=\"this.style.background='#fff'\" onmouseover=\"this.style.background='#f6f9fd'\" style=\"background: none repeat scroll 0% 0% rgb(255, 255, 255);\">
                    <td class=\"fenlei td_left\">$prefix_space $fuhao <a href='" . PHP_SELF . "?m=archives.arclist&channelid=$v[channeltype]&cat_id=$v[cat_id]'>$v[cat_name]</a></td>
                    <td class='td_left'>$v[category_nicename]</td>
                    <td class='td_left'>$category_content</td>
                    <td align='center'><a href='" . PHP_SELF . "?m=archives.catgoto&channelid=$v[channeltype]&cat_id=$v[cat_id]'>发布内容</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href='" . PHP_SELF . "?m=archives.arclist&channelid=$v[channeltype]&cat_id=$v[cat_id]'>查看内容</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href='" . PHP_SELF . "?m=category.add&cat_id=$v[cat_id]'>修改</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a onclick=\"{if(confirm('删除将包括该分类的所有信息，确定删除吗?')){return true;}return false;}\"href=\"" . PHP_SELF . "?m=category.del&cat_id=$v[cat_id]\">删除</a></td>
                    </tr>";
                //echo "<option value=".$v['id'].$select.">".$prefix_space."|-".$v['typename'].$v[id]."</option><br>";
                $this->getCategory($uid, $v['cat_id'], $level + 1); //存在下一级就再次递归调用函数
            }
        }
        return $elo; //最后返回树形菜单
    }

    /**
     * 取分类列表
     * @global type $category_list
     * @param type $parent
     * @param type $url
     * @param type $uid
     * @param type $username
     * @param type $indexurl
     * @return type 
     */
    public function getCategoryList($parent, $uid)
    {
        $catetory_array = $this->getCategoryArray($uid);
        global $category_list;
        $category_list = '';
        $category_list = $this->fenlei($catetory_array, $parent);
        $this->assign('category_list', $category_list);
        return $category_list;
    }

    /**
     * 取出所有Category数组
     * @param type $uid
     * @return type 
     */
    public function getCategoryArray($uid)
    {
        if ($uid > 1) {
            $sqltree = "SELECT a.cat_id,a.cat_pid,a.cat_name,a.category_nicename,a.channeltype,b.content AS category_content, b.cat_name AS cat_name_add, b.channeltype AS channeltype_add, b.cat_pid AS cat_pid_add FROM $this->category_table a LEFT JOIN $this->add_category_table b ON a.cat_id = b.cat_id AND b.uid = '{$uid}' WHERE (a.uid = '{$uid}' OR a.uid = 1) AND a.cat_type = 0 ORDER BY a.cat_order DESC, a.cat_id ASC";
        } else {
            $sqltree = "SELECT cat_id,cat_pid,cat_name,channeltype,category_nicename,category_content FROM $this->category_table WHERE uid = 1 ORDER BY cat_order DESC, cat_id ASC";
        }       
        $rs = $this->db->getAll($sqltree);
        if ($uid > 1) {
            if (is_array($rs)) {
                foreach ($rs AS $k => $v) {
                    $rs[$k]['cat_pid'] = empty($v['cat_pid_add']) ? $v['cat_pid'] : $v['cat_pid_add'];
                    $rs[$k]['cat_name'] = empty($v['cat_name_add']) ? $v['cat_name'] : $v['cat_name_add'];
                    $rs[$k]['channeltype'] = empty($v['channeltype_add']) ? $v['channeltype'] : $v['channeltype_add'];
                }
            }
        }
//        echo $sqltree;
//        var_dump($rs);
        return $rs;
    }

    /**
     * 取无限分类
     * @global type $category_list
     * @param type $arr
     * @param type $parent
     * @param type $url
     * @param type $username
     * @param type $indexurl
     * @return string 
     */
    public function fenlei($arr, $parent)
    {
        global $category_list; //定义全局变量 返回值        
        $BASE_V = 'Public/' . APP_NAME . '/';
        $num = count($arr);

        for ($i = 0; $i < $num; $i++) {//循环该层
            if ($i == 0) {
                for ($j = 0; $j < $num; $j++) {
                    if ($arr[$j]['cat_pid'] == $parent) {
                        $category_list .= '<ul class="category_list" style="padding:0px">';
                        break;
                    }//有元素的该层开始是输出<ul>，
                }
            }
            if ($arr[$i]['cat_pid'] == $parent) {  //层中符合父级id的元素输出                 
                $arr_array = $arr[$i];
                $category_content = Functions::cut_str(strip_tags($arr_array['category_content']), 42);
                $category_content = empty($category_content) ? '&nbsp;' : $category_content;
                $category_list .= "<li><dl>                
                    <dd class='cl_one'><div class='cate'><img src=\"{$BASE_V}images/desc.gif\" title='展开/收缩'><a href=\"" . PHP_SELF . "?m=archives.arclist&channelid=" . $arr_array['channeltype'] . "&cat_id=" . $arr_array['cat_id'] . "\">" . $arr_array['cat_name'] . "</a></div></dd>
                    <dd class='cl_two'>" . $arr_array['category_nicename'] . "</dd>
                    <dd class='cl_three'>$category_content</dd>                            
                    <dd class='cl_four'><a href=\"" . PHP_SELF . "?m=archives.catgoto&channelid=" . $arr_array['channeltype'] . "&cat_id=" . $arr_array['cat_id'] . "\">发布内容</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href=\"" . PHP_SELF . "?m=archives.arclist&channelid=" . $arr_array['channeltype'] . "&cat_id=" . $arr_array['cat_id'] . "\">查看内容</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href=\"" . PHP_SELF . "?m=category.add&cat_id=" . $arr_array['cat_id'] . "\">修改</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a onclick=\"{if(confirm('删除将包括该分类的所有信息，确定删除吗?')){return true;}return false;}\"href=\"" . PHP_SELF . "?m=category.del&cat_id=" . $arr_array['cat_id'] . "\">删除</a></dd></dl>";
                $this->fenlei($arr, $arr[$i]['cat_id']);  //递归执行寻找当前元素的子元素，这些子元素<ul><li>当前元素<ul><li>子元素</li></ul></li></ul>
                $category_list .= "</li>";      //该</li>放在fenlei函数后是为了把形成该元素的子元素也要包含在该元素的<li>内
            }
            if ($i == ($num - 1)) {
                for ($j = 0; $j < $num; $j++) {
                    if ($arr[$j]['cat_pid'] == $parent) {
                        $category_list .= "</ul>";
                        break;
                    }//闭合ul
                }
            }
        }
        return $category_list;
    }

    /**
     * del
     * @param int $class_id
     */
    public function delClass($cat_id)
    {
        $rs = $this->db->execute("DELETE FROM $this->category_table WHERE cat_id = $cat_id");
        $rs = $this->db->execute("DELETE FROM $this->add_category_table WHERE cat_id = $cat_id");
        return $rs;
    }

    /**
     * 递归获取分类数组
     *
     * @param int $reid			    父级id
     * @param int $level			级别
     * @param int $current_id		当前编辑的分类id
     * @param int $tabel			要查询sql table
     * @param int $where			要查询sql where
     */
    public function tree($uid, $reid, $level, $current_id, $table="#@__category")
    {
        global $el; //定义全局变量 返回值
        $prefix_space = "";
        for ($i = 0; $i < $level; $i++) {
            $prefix_space .= "　"; //第一级就增加一个缩进
        }

        if ($uid > 1) {
            $sqltree = "SELECT cat_id, cat_pid, cat_name FROM " . $table . " WHERE cat_pid = " . $reid . " AND (uid = '{$uid}' OR uid = 1) AND cat_type = 0 ORDER BY cat_order DESC, cat_id ASC";
        } else {
            $sqltree = "SELECT cat_id, cat_pid, cat_name FROM " . $table . " WHERE cat_pid = " . $reid . "  AND uid = 1 ORDER BY cat_order DESC, cat_id ASC";
        }
        $rs = $this->db->getAll($sqltree);
        if (is_array($rs)) {
            foreach ($rs as $k => $v) {
                if ($v['cat_id'] === $current_id) {
                    $select = " selected";
                } else {
                    $select = "";
                }
                $el .= '<option value="' . $v['cat_id'] . '" ' . $select . '>' . $prefix_space . '|-' . $v['cat_name'] . '</option><br>';
                //echo "<option value=".$v['id'].$select.">".$prefix_space."|-".$v['typename'].$v[id]."</option><br>";
                $this->tree($uid, $v['cat_id'], $level + 1, $current_id, $table); //存在下一级就再次递归调用函数
            }
        }
        return $el; //最后返回树形菜单
    }

    /**
     * 取Select list
     * @global string $category_tree_list
     * @param type $parent
     * @param type $uid
     * @param type $current_id
     * @return string 
     */
    public function getCategoryTreeList($parent, $uid, $current_id)
    {
        $catetory_array = $this->getCategoryArray($uid);
        global $category_tree_list;
        $category_tree_list = '';
        $category_tree_list = $this->tree_fenlei($catetory_array, $parent, 0, $current_id);
        $this->assign('category_tree_list', $category_tree_list);
        return $category_tree_list;
    }

    /**
     * 递归取select option
     * @global string $category_tree_list
     * @param type $arr
     * @param type $parent
     * @param type $level
     * @param type $current_id
     * @return string 
     */
    public function tree_fenlei($arr, $parent, $level, $current_id)
    {
        global $category_tree_list; //定义全局变量 返回值        
        $BASE_V = 'Public/' . APP_NAME . '/';
        $num = count($arr);
        $prefix_space = '';
        for ($j = 0; $j < $level; $j++) {
            $prefix_space .= "　"; //第一级就增加一个缩进            
        }

        for ($i = 0; $i < $num; $i++) {//循环该层
            if ($arr[$i]['cat_pid'] == $parent) {  //层中符合父级id的元素输出                 
                $arr_array = $arr[$i];
                if ((int) $arr_array['cat_id'] === (int) $current_id) {
                    $select = " selected";
                } else {
                    $select = "";
                }
                $category_tree_list .= '<option value="' . $arr_array['cat_id'] . '" ' . $select . '>' . $prefix_space . '|-' . $arr_array['cat_name'] . '</option>';
                $this->tree_fenlei($arr, $arr[$i]['cat_id'], $level + 1, $current_id);  //递归执行寻找当前元素的子元素，这些子元素<ul><li>当前元素<ul><li>子元素</li></ul></li></ul>                
            }
        }
        return $category_tree_list;
    }

    /**
     * 取所有的子ID
     * @global type $son_tree_list
     * @param type $parent
     * @return type 
     */
    public function getSonTreeList($parent, $uid)
    {
        $catetory_array = $this->getCategoryArray($uid);
        global $son_tree_list;
        $son_tree_list = '';
        $son_tree_list = $this->son_fenlei($catetory_array, $parent);

        if (empty($son_tree_list)) {
            $cat_id_rs = $parent;
        } else {
            $cat_id_rs = $son_tree_list . ',' . $parent;
            $cat_id_rs = substr($cat_id_rs, 1);
        }
        $this->assign('son_tree_list', $cat_id_rs);
        return $cat_id_rs;
    }

    /**
     * 取所有的子ID
     * @global type $son_tree_list
     * @param type $arr
     * @param type $parent
     * @return type 
     */
    public function son_fenlei($arr, $parent)
    {
        global $son_tree_list; //定义全局变量 返回值        
        $num = count($arr);

        for ($i = 0; $i < $num; $i++) {//循环该层
            if ($arr[$i]['cat_pid'] == $parent) {  //层中符合父级id的元素输出                 
                $arr_array = $arr[$i];
                $son_tree_list .= ',' . $arr_array['cat_id'];
                $this->son_fenlei($arr, $arr[$i]['cat_id']);  //递归执行寻找当前元素的子元素，这些子元素<ul><li>当前元素<ul><li>子元素</li></ul></li></ul>                
            }
        }

        return $son_tree_list;
    }

    /**
     * 判断用户对此线路类别是否有操作权限
     * @param <type> $id
     * @return <type>
     */
    public function checkUser($id, $uid)
    {
        $info = $this->getCategoryInfo($id, $uid);
        if ($info['uid'] == $uid) {
            return true;
        } else {
            $this->redirect('没有相关操作权限');
            exit;
        }
    }

    /**
     * 判断用户对此机构栏目有权限
     * @param <type> $id
     * @return <type>
     */
    public function checkUserCat($id, $uid)
    {
        $info = $this->getCategoryInfo($id, $uid);
        if ($info['cat_type'] == 1) {
            if ($uid == $info['uid']) {
                return true;
            } else {
                $this->redirect('没有相关操作权限');
                exit;
            }
        }
    }

    /**
     * 判断用户对此线路类别是否有操作权限
     * @param <type> $id
     * @return <type>
     */
    public function checkUserReturn($id, $uid)
    {
        $info = $this->getCategoryInfo($id, $uid);
        if ($info['uid'] == $uid) {
            return true;
        } else {
            return false;
        }
    }

}